/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.univali.sindico.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;

/**
 *
 * @author Fernando
 */
public class GenericDAO <T>{
    
    protected SessionFactory sessionFactory;
    private Class<T> persistentClass;
    
    public GenericDAO() {  
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass()  
                                .getGenericSuperclass()).getActualTypeArguments()[0];  
        sessionFactory = HibernateUtil.getSessionFactory();
     } 
    
    public List<T> getAll(){
        Session session = sessionFactory.openSession();
        List<T> result = session.createCriteria(persistentClass).list();
        session.close();
        return result;
    }
         
    public T getById(long id){
        Session session = sessionFactory.openSession();
        return (T)session.get(persistentClass, id);
    }
    
    public void save(T type){
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();  
        session.saveOrUpdate(type);
        t.commit();
        session.close();
    }
    
    public void delete(T type){
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();
        session.delete(type);
        t.commit();
        session.close();
    }
    
    public void update(T type){
        Session session = sessionFactory.openSession();
        Transaction t = session.beginTransaction();  
        session.update(type);
        t.commit();
        session.close();
    }
        
}
